/**
 * byte_buffer 简单的字节缓冲区
 * 张勇 41204@qq.com
 */

#include "byte_buffer.h"

unios_ms_t byte_buffer_age(byte_buffer_t* buf) {
	return unios_ms_elapsed(buf->timestamp);
}

void byte_buffer_lshift(byte_buffer_t* buf, size_t nbytes) {
	if(!buf || !buf->dlen || !nbytes) { return; }
	if(buf->dlen > nbytes) {
		buf->dlen -= nbytes;
		memcpy(buf->data, buf->data+nbytes, buf->dlen);
	} else {
		buf->dlen = 0;
	}
}

std_err_t byte_buffer_putc(byte_buffer_t* buf, char ch) {
	if(!buf) { return STD_ERR_INVALID_ARG; }
	if(buf->dlen >= buf->size-1) { return STD_ERR_BUFFER_OVERFLOW; }
	buf->data[buf->dlen] = ch; buf->dlen++;
	buf->timestamp = unios_ms_now();
	return STD_ERR_OK;
}

std_err_t byte_buffer_put(byte_buffer_t* buf, size_t len, const uint8_t* data) {
	if(!buf || !len || !data) { return STD_ERR_INVALID_ARG; }
	if(buf->dlen + len > buf->size-1) { return STD_ERR_BUFFER_OVERFLOW; }
	memcpy(buf->data + buf->dlen, data, len); buf->dlen += len;
	buf->timestamp = unios_ms_now();
	return STD_ERR_OK;
}
